package com.epoint.mobileoa.ui.login;

import java.util.HashMap;

import org.taptwo.android.widget.viewflow.example.MainViewFlow;

import com.epoint.mobileoa.R;
import com.epoint.mobileoa.bizlogic.ConfigKey;
import com.epoint.mobileoa.bizlogic.SkipFlag;
import com.epoint.mobileoa.bizlogic.SuperView;
import com.epoint.mobileoa.bizlogic.Task;
import com.epoint.mobileoa.bizlogic.mobileoa.CheckLoginTask;
import com.epoint.mobileoa.db.DBHelp;
import com.epoint.mobileoa.http.HttpHelp;
import com.epoint.mobileoa.service.MainService;
import com.epoint.mobileoa.tools.AlertHelp;
import com.epoint.mobileoa.tools.AnimationHelp;
import com.epoint.mobileoa.tools.MDUtil;
import com.epoint.mobileoa.tools.StringHelp;
import com.epoint.mobileoa.tools.ToastHelp;
import com.epoint.mobileoa.ui.contacts.ContactsView;
import com.epoint.mobileoa.ui.help.HelpView;
import com.epoint.mobileoa.ui.main.MainView;
import com.epoint.mobileoa.ui.main.MainViewNew;
import com.epoint.mobileoa.ui.statistics.StatisticsMain;
import com.epoint.mobileoa.ui.statistics.StatisticsView;
import com.epoint.mobileoa.ui.sysconfig.SysconfigView;

import android.content.Intent;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.TextView;

/**
 * @author liyc
 * @time 2012-1-6 下午2:37:25
 * @annotation 登录控制模块
 */
public class LoginView extends SuperView{

	private EditText password_et;
	private AutoCompleteTextView username_et;
	private Button loginBtn, cleanBtn;
	private CheckBox cbRempsw, cbAutologin,tjdl,msgtip;
	public static final int REFRESH_LOGIN = 1;

	private TextView tvVersion;

	private String username;
	private String password_jm;

	@Override
	public void initControls() {
		loginBtn = (Button) findViewById(R.id.loginbtn);
		username_et = (AutoCompleteTextView) findViewById(R.id.username_et);
		password_et = (EditText) findViewById(R.id.password_et);
		cbRempsw = (CheckBox) findViewById(R.id.rem_pswcb);
		cbAutologin = (CheckBox) findViewById(R.id.autologincb);
		tjdl = (CheckBox) findViewById(R.id.lg_tj);
		msgtip = (CheckBox) findViewById(R.id.lg_msgtip);
		loginBtn.setOnClickListener(this);
		tvVersion = (TextView) findViewById(R.id.tvVersion);
		tvVersion.setText("V"+getString(R.string.version));
		top_left_bt.setVisibility(View.GONE);
		showTopRightBtn("设置");
		//网络监测线程暂时不运行
		MainService.isNetCheck = false;
		//更新登陆状态暂时不运行
		MainService.isrefreshloginstatusflag = false;

		username_et.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				password_et.setText("");
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {

			}

			@Override
			public void afterTextChanged(Editable s) {

			}
		});

		//如果不是从初始化页跳转过来，是从其他页面跳转过来，则提示系统在其他设备上已经登陆
		int mainserviceguitflag = getIntent().getIntExtra(SkipFlag.SKIP_TAG, 0);
		if(mainserviceguitflag==1){
			AlertHelp.ShowAlert(this, getString(R.string.another_device_login_warning));
		}

		//加入勾选了自动登录，则记住密码也勾选
		cbAutologin.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				if(isChecked){
					cbRempsw.setChecked(true);
				}
			}
		});
		
		cbRempsw.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				if(!isChecked){
					cbAutologin.setChecked(false);
				}
			}
		});
		
		
	}

	@Override
	public String setTitle() {
		return "登录";
	}

	@Override
	public int getLayoutInt() {
		if(DBHelp.getConfigValue(this, ConfigKey.backgroundcolor).equals("background"))
			return R.layout.login2_background;
		else
			return R.layout.loginepoint;
		//return R.layout.login;
	}

	@Override
	public void onClick(View v) {
		if(v==loginBtn){
			login();
		}
		else if(v==cleanBtn){
			username_et.setText("");
			password_et.setText("");
		}
		else if(v==top_right_bt)
		{
			Intent it_sysconfigview = new Intent(this, SysconfigView.class);
			startActivity(it_sysconfigview);
		}
	}

	public void login(){
		if(username_et.getText().toString().equals("epoint")&&password_et.getText().toString().equals("epoint")){
			Intent intent = new Intent(this, MainView.class);
			startActivity(intent);
			finish();
		}
		else{
			if(tjdl.isChecked()){
				DBHelp.setConfigValue(this, ConfigKey.isTuojiLogin, "1");
				Intent it_txl = new Intent(this,ContactsView.class);
				startActivity(it_txl);
			}
			else{
				DBHelp.setConfigValue(this, ConfigKey.isTuojiLogin, "0");

				if(username_et.getText().toString().trim().length()==0
						||password_et.getText().toString().trim().length()==0){
					ToastHelp.showToast(this, "用户名或密码不能为空！", 1000);
					if(username_et.getText().toString().trim().length()==0){
						AnimationHelp.shake(this, username_et);
					}
					if(password_et.getText().toString().trim().length()==0){
						AnimationHelp.shake(this, password_et);
					}
				}
				else{
					showDialog_wait("正在验证您的身份...");
					username = username_et.getText().toString();
					password_jm = MDUtil.authPassword(password_et.getText().toString().trim());

					HashMap<String,Object> param=new HashMap<String,Object>();
					param.put("loginid", username);
					param.put("password", password_jm);

					Task task = new CheckLoginTask(this, param);
					MainService.addTask(task);
				}
			}
		}
	}

	@Override
	public void refresh(Object... param) {

		m_Dialog.dismiss();

		if(param[0].toString().equals(MainService.NORMAL)){
			String bs = param[1].toString();
			if(bs.contains(HttpHelp.RESPONSEINFO_SUCCESS)){
				String unreadMailNums = StringHelp.getXMLAtt(bs, "unreadMainNums");
				Intent intent = new Intent(this, MainViewFlow.class);
				intent.putExtra("unreadMailNums", unreadMailNums);
				startActivity(intent);
				finish();
				if(cbRempsw.isChecked()){
					DBHelp.setConfigValue(this, ConfigKey.rempass, "1");
					DBHelp.setConfigValue(this, ConfigKey.pw_un, password_et.getText().toString());
				}
				else{
					DBHelp.setConfigValue(this, ConfigKey.rempass, "0");
				}
				if(cbAutologin.isChecked()){
					DBHelp.setConfigValue(this, ConfigKey.autologin, "1");
				}
				else{
					DBHelp.setConfigValue(this, ConfigKey.autologin, "0");
				}
				if(msgtip.isChecked()){
					DBHelp.setConfigValue(this, ConfigKey.isMessageTip, "1");
				}
				else{
					DBHelp.setConfigValue(this, ConfigKey.isMessageTip, "0");
				}

				//更改是否登录字段
				DBHelp.setConfigValue(this, ConfigKey.isLogin, "1");

				//更新登陆历史记录表
				DBHelp.updateLoginHistory(this,username_et.getText().toString().trim());

				String userguid = StringHelp.getXMLAtt(bs, "userguid");
				String displayName = StringHelp.getXMLAtt(bs, "displayname");
				String isAdmin = StringHelp.getXMLAtt(bs, "isAdmin");
				DBHelp.setConfigValue(this, ConfigKey.loginid, username_et.getText().toString());
				DBHelp.setConfigValue(this, ConfigKey.password, password_jm);
				DBHelp.setConfigValue(this, ConfigKey.userguid, userguid);
				DBHelp.setConfigValue(this, ConfigKey.displayname,
						displayName);
				DBHelp.setConfigValue(this, ConfigKey.isAdmin,
						isAdmin);
				fp.setDisplayname(displayName);
				fp.setLoginid(username_et.getText().toString());
				fp.setUserguid(userguid);
				fp.setPassword(password_jm);
			}
			else if(bs.startsWith(HttpHelp.RESPONSEINFO_FAILURE)){
				AnimationHelp.shake(this, loginBtn);
				ToastHelp.showToast(this, "用户名或密码错误！", 1000);
			}
			else if(bs.equals("Register_Error")){
				ToastHelp.showToast(this, "移动办公身份未通过验证！", 1000);
			}
			else if(bs.equals("Register_ShenHeZhong")){
				ToastHelp.showToast(this, "移动办公身份正在审核中！", 1000);
			}
			else if(bs.equals("Register_ShenHeFailure")){
				ToastHelp.showToast(this, "移动办公身份审核未通过！", 1000);
			}
			else if(bs.equals("<Check>Admin</Check>")){
				Intent it = new Intent(this,StatisticsMain.class);
				startActivity(it);
			}
		}
	}
	
	@Override
	protected void onResume() {
		super.onResume();


		//设置是否登陆状态为未登录
		DBHelp.setConfigValue(this, ConfigKey.isLogin, "0");

		//加入脱机登陆勾选,则取消自动登陆
		if(tjdl.isChecked()){
			cbAutologin.setChecked(false);
			DBHelp.setConfigValue(this, ConfigKey.autologin, "0");
		}

		//启动服务
		Intent serviceIntent = new Intent(MainService.Name);
		startService(serviceIntent);

		//是否记住密码
		String rempass = DBHelp.getConfigValue(this, ConfigKey.rempass);
		if(rempass.equals("1")){
			username_et.setText(DBHelp.getConfigValue(this, ConfigKey.loginid));

			String upw = DBHelp.getConfigValue(this, ConfigKey.pw_un);

			int gdlenght = 10;

			if(upw.length()<gdlenght){
				int bk = gdlenght-upw.length();

				for(int i=0;i<bk;i++){
					upw += " ";
				}
			}
			password_et.setText(upw);
			cbRempsw.setChecked(true);
		}

		//是否消息提示
		String isMessageTip = DBHelp.getConfigValue(this, ConfigKey.isMessageTip);
		if(isMessageTip.equals("1")){
			msgtip.setChecked(true);
		}
		else{
			msgtip.setChecked(false);
		}

		//是否脱机登陆
		String isTuojiLogin = DBHelp.getConfigValue(this, ConfigKey.isTuojiLogin);
		if(isTuojiLogin.equals("1")){
			tjdl.setChecked(true);
		}
		else{
			tjdl.setChecked(false);
		}

		//是否自动登陆
		String autologin = DBHelp.getConfigValue(this, ConfigKey.autologin);
		if(autologin.equals("1")){
			cbAutologin.setChecked(true);
			login();
		}
		else{
			cbAutologin.setChecked(false);
		}

		//设置用户名下拉选项adapter
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, 
				R.layout.autocompleteview_list_item, DBHelp.getLoginHistoryInfo(this));
		username_et.setAdapter(adapter);
	
//		username_et.setText("epoint");
//		password_et.setText("mobileoa2012");
	}


	@Override
	public void KEYCODE_BACK() {
		MainService.quitApplication(LoginView.this);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(0, 1, 1, getString(R.string.xtsz)).setIcon(
				R.drawable.menu_system_setting);
		menu.add(0, 2, 2, "帮助说明").setIcon(R.drawable.menu_help);
		menu.add(0, 3, 3, "用户注册").setIcon(R.drawable.menu_register);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		super.onOptionsItemSelected(item);
		switch (item.getItemId()) {
		case 1:
			Intent it_sysconfigview = new Intent(this, SysconfigView.class);
			startActivity(it_sysconfigview);
			break;
		case 2:
			Intent it_help = new Intent(this, HelpView.class);
			startActivity(it_help);
			break;
		case 3:
			Intent it_register = new Intent(this,RegisterView.class);
			startActivity(it_register);
			break;
		}
		return true;
	}

	@Override
	public void refreshForNewTask(int TaskId,Object... param) {
	}

}
